package server

import (
	"context"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/internal/services/nami/services/sports/basketball/bbcache"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/protobuf"
	"strconv"
	"strings"
	"time"
)

func (s *Server) LivePreview(c context.Context, req *protobuf.LivePreviewReq) (*protobuf.LivePreviewResp, error) {
	var err error
	var ret []*protobuf.LivePreview
	var resp []*protobuf.LivePreview
	var timeRangeB, timeRangeE int64
	if req.Date == 1 { //今天
		timeRangeB, timeRangeE = timehelper.INaDay2Unix(time.Now().Format("2006-01-02"))
	}
	if req.Date == 2 { // 明天
		timeRangeB, timeRangeE = timehelper.INaDay2Unix(time.Now().Add(24 * time.Hour).Format("2006-01-02"))
	}
	if req.Date == 3 { // 后天
		timeRangeB, timeRangeE = timehelper.INaDay2Unix(time.Now().Add(48 * time.Hour).Format("2006-01-02"))
	}
	query := global.Live().Table("db_live_preview")
	if req.AnchorId > 0 {
		// 如果传主播去掉时间范围
		timeRangeB, _ = timehelper.INaDay2Unix(time.Now().Format("2006-01-02"))
		query.Where("match_time>=?", timeRangeB)
	} else {
		query.Where("match_time>=? and match_time<=?", timeRangeB, timeRangeE)
	}
	if req.SportId != 0 && req.SportId != 3 {
		query.Where("sport_id=?", req.SportId)
	}
	if req.SportId == 3 {
		query.Where("sport_id not in (?,?)", _const.FOOT_BALL_SPORT_ID, _const.BASKET_BALL_SPORT_ID)
	}
	if req.AnchorId > 0 {
		query.Where("anchor_ids like ?", "%"+fmt.Sprintf("%d", req.AnchorId)+"%")
	}
	err = query.Order("match_time asc").Scan(&ret).Error
	if err != nil {
		global.Log.Errorf("LivePreview err:%v", err)
		return &protobuf.LivePreviewResp{
			LivePreview: ret,
		}, err
	}

	var matchIDs []interface{}

	for idx, v := range ret {
		//进行中为赛事状态不是直播状态
		// var _check int64
		// global.Live().Model(&models_live.Live{}).Where("matchid=?", v.MatchId).Count(&_check)
		// if _check != 0 {
		// 	ret[idx].Status = 1
		// }

		// 比赛状态 id
		matchIDs = append(matchIDs, v.MatchId)

		if v.AnchorIds != "" {
			ids := strings.Split(v.AnchorIds, ",")
			for _, i := range ids {
				uid, _ := strconv.Atoi(i)
				anchor, _ := cache.GetUserFullInfo(uid)
				ret[idx].Anchors = append(ret[idx].Anchors, &protobuf.LiveAnchor{
					Id:       int64(anchor.Id),
					Nickname: anchor.NickName,
					Avatar:   anchor.Avatar,
				})
			}
		}
	}
	scoresList := bbcache.NewScoreCache().GetScoreRedisCache(matchIDs)
	var match []models_sports.MatchTempSchedule
	err = global.Sport().Model(&models_sports.MatchTempSchedule{}).Where("match_id in ?", matchIDs).Find(&match).Error
	if err != nil {
		global.Log.Errorf("preview error:", err)
	}

	for idx, v := range ret {
		found := false
		for _, m := range match {
			if v.MatchId == int64(m.MatchId) && int(v.SportId) == m.SportId {
				if m.MatchStatus >= 3 {
					found = true
					break
				}
				ret[idx].TimePlayed = int32(m.TimePlayed)
				ret[idx].HomeScore = int32(m.HomeScore)
				ret[idx].AwayScore = int32(m.AwayScore)
				ret[idx].MatchStatus = m.MatchDetailStatus
				ret[idx].MatchStatusCode = int32(m.MatchStatus)

				if m.MatchStatus == 2 {
					ret[idx].Status = 0
				} else {
					ret[idx].Status = int32(m.MatchStatus)
				}
				break
			}
		}
		if found {
			continue
		}

		for _, b := range scoresList {
			if int64(b.MatchId) == v.MatchId {
				for i := 0; i < len(b.HomeScore); i++ {
					ret[idx].BasketHomeScores = append(ret[idx].BasketHomeScores, int32(b.HomeScore[i]))
				}
				for i := 0; i < len(b.AwayScore); i++ {
					ret[idx].BasketAwayScores = append(ret[idx].BasketAwayScores, int32(b.AwayScore[i]))
				}
				break
			}
		}

		resp = append(resp, ret[idx])
	}

	// 收藏
	if req.UserId > 0 {
		var fav []models_sports.MatchFavorite
		err = global.Sport().Model(&fav).Where("match_id in ? and user_id=?", matchIDs, req.UserId).Find(&fav).Error

		if err != nil {
			global.Log.Errorf("preview favorite error:", err)
		}

		for idx, v := range resp {
			for _, f := range fav {
				if v.MatchId == int64(f.MatchId) && int(v.SportId) == f.SportId {
					resp[idx].Favorite = 1
					break
				}
			}
		}
	}

	return &protobuf.LivePreviewResp{
		LivePreview: resp,
	}, nil
}
